/**
 * Created by lenovo on 2019/5/30.
 */
function MusicDemo(obj) {

    this.source = null;

    this.count = 0;

    this.analyser = MusicDemo.ac.createAnalyser();
    this.size = obj.size;
    this.analyser.fftSize = this.size * 2;

    this.gainNode = MusicDemo.ac[ac.createGain ? "createGain" : "createGainNode"]();

    this.gainNode.connect(MusicDemo.ac.destination);

    this.analyser.connect(this.gainNode);

    this.xhr = new XMLHttpRequest();

    this.visualizer = obj.visualizer;

    this.visualize();
}

MusicDemo.ac = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext)();

MusicDemo.prototype.load = function (url) {

    // 中止上一次的请求
    xhr.abort();
    xhr.open("GET", url);
    xhr.responseType = "arraybuffer";
    var self = this;
    xhr.onload = function () {
        fun(self.xhr.response);
    }
    xhr.send();
}

MusicDemo.prototype.decode = function (arrayBuffer, fun) {
    MusicDemo.ac.decodeAudioData(arrayBuffer, function (buffer) {
        fun(buffer);
    }, function (err) {
        console.log(err);
    });
}

MusicDemo.prototype.paly = function (url) {
    var n = ++this.count;
    var self = this;
    // 停止正在播放的音频
    this.source && this.stop();
    this.load(url, function (arraybuffer) {
        if(n != self.count)return;
        self.decode(arraybuffer, function (buffer) {
            var bs = MusicDemo.ac.createBufferSource();
            bs.buffer = buffer;
            bs[bs.start ? "start": "noteON"](0);
            self.source = bs;
        })
    });
}

MusicDemo.prototype.stop = function () {
    this.source[this.source.stop ? "stop" : "noteOff"](0);
}

MusicDemo.prototype.changeVolume = function (percent) {
    if(this.gainNode && this.gainNode.gain){
        this.gainNode.gain.value = percent * percent;
    }
}

MusicDemo.prototype.visualize = function () {
    var arr = new Uint8Array(this.analyser.frequencyBinCount);
    /**
     * 用 requestAnimationFrame 和 <canvas> 去反复收集当前音频的时域数据, 并绘制为一个示波器风格的输出(频谱).
     * https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestAnimationFrame
     */
    requestAnimationFrame = window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame;
    var self = this;
    function v() {
        self.analyser.getByteFrequencyData(arr);
        //console.log(arr);
        //draw(arr);
        self.visualizer(arr);
        requestAnimationFrame(v);
    }
    requestAnimationFrame(v);
}